package kp.rpc.fault.retry.impl;

import com.github.rholder.retry.*;
import kp.rpc.fault.retry.RetryStrategy;
import kp.rpc.model.RpcResponse;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * @author tzf
 * @description: 固定重试策略
 * @date: 2024/6/7 14:02
 */
@Slf4j
public class FixedIntervalRetryStrategy implements RetryStrategy {

    @Override
    public RpcResponse doRetry(Callable<RpcResponse> callable) throws Exception {
        log.info("FixedIntervalRetryStrategy");
        Retryer<RpcResponse> retryer = RetryerBuilder.<RpcResponse>newBuilder().
                //重试条件->重试条件->异常
                        retryIfExceptionOfType(Throwable.class).
                //重试策略->固定等待->等待策略->固定等待时间->3L&seconds
                        withWaitStrategy(WaitStrategies.fixedWait(3L, TimeUnit.SECONDS))
                //重试次数
                .withStopStrategy(StopStrategies.stopAfterAttempt(3)).
                //设置监听->每次重试打印日志
                        withRetryListener(new RetryListener() {
                    @Override
                    public <V> void onRetry(Attempt<V> attempt) {
                        log.warn("{}重试次数{}!", LocalDateTime.now(), attempt);
                    }
                }).build();
        return retryer.call(callable);
    }
}
